package com.bdqn;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.FileOutputStream;
import java.io.IOException;

public class Sjlx2xz {
    public static void main(String[] args) {
        //工厂实例
        DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();
        //获取DOM解析器
        try {
            DocumentBuilder db=dbf.newDocumentBuilder();
            //解析xml文件返回Document对象
            Document document=db.parse("ch02/Practical/手机收藏信息.xml");
            Element element=document.createElement("Brand");
            element.setAttribute("name","三星");
            Element type=document.createElement("type");
            type.setAttribute("name","Notex");
            element.appendChild(type);
            Element phone=(Element)document.getElementsByTagName("Phone").item(0);
            phone.appendChild(element);
            //保存XML文件
            TransformerFactory factory=TransformerFactory.newInstance();
            Transformer transformer=factory.newTransformer();
            DOMSource domSource=new DOMSource(document);
            //设置字符编码
            transformer.setOutputProperty(OutputKeys.ENCODING,"UTF-8");
            StreamResult result= new StreamResult(new FileOutputStream("ch02/Practical/手机收藏信息.xml"));
            transformer.transform(domSource,result);
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TransformerConfigurationException e) {
            e.printStackTrace();
        } catch (TransformerException e) {
            e.printStackTrace();
        }
    }


}
